<?php
// +----------------------------------------------------------------------
// | 应用公共文件
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

use think\facade\Config;
use think\facade\Cache;
use think\Response;
use app\model\ucenter\User;
use think\helper\Str;
use think\facade\Lang as LangThink;
use app\common\model\Lang as LangModel;
use wechat\mch\Pay as WechatMchPay;

/**
 * 处理事件
 *
 * @param string $event
 *            钩子名称
 * @param mixed $args
 *            传入参数
 * @param bool $once
 *            只获取一个有效返回值
 * @return void
 */
function event($event, $args = [], $once = false)
{
    $res = \think\facade\Event::trigger($event, $args);
    if (is_array($res)) {
        $res = array_filter($res);
        sort($res);
    }
    //只返回一个结果集
    if ($once) {
        return $res[0] ?? '';
    }
    return $res;

}

/**
 * 验证身份证号码并提取出生时间
 * @param $id
 * @return false|int|string
 */
function get_idcard_birthday($id)
{
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if (!preg_match($regx, $id)) {
        return false;
    }
    if (15 == strlen($id)) {//检查15位
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19" . $arr_split[2] . '-' . $arr_split[3] . '-' . $arr_split[4];
        if (!strtotime($dtm_birth)) {
            return false;
        } else {
            return $dtm_birth;
//            //提取年龄
//            $age = date("Y") - (int)substr($id, 6, 2);
//            return $age;
        }
    } else {//检查18位
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '-' . $arr_split[3] . '-' . $arr_split[4];
        if (!strtotime($dtm_birth)) {//检查生日日期是否正确
            return false;
        } else {
            return $dtm_birth;
            //提取年龄
//            $age = date("Y") - (int)substr($id, 6, 4);
//            return $age;
        }
    }
}

function money_format($money)
{
    return sprintf("%.2f", $money);
}

/**
 * 二图合二为一
 * @param $img
 * @param $avatarUrl
 * @param $patch
 * @return string
 */
function createShare($img, $avatarUrl, $patch, $return_file, $cid = 0)
{
    $thumb = imagecreatetruecolor(285, 285);     //创建一个新的画布（缩放后的），从左上角开始填充透明背景
    list($src_w, $src_h) = getimagesize('.' . $avatarUrl);
    $img_content = imagecreatefrompng('.' . $avatarUrl);//获取图片资源
    imagecopyresampled($thumb, $img_content, 0, 0, 0, 0, 285, 285, $src_w, $src_h);//核心函数，改变图片大小
    $file_name = './upload/test/' . uniqid() . '.png';
    imagepng($thumb, $file_name);//将图片资源保存到qrcode_1.png中
    //2、将缩小的二维码合成到海报中
//    $img = '.'.ltrim($img,'.');
    $ename = getimagesize($img);
    $ename = explode('/', $ename['mime']);
    $ext = $ename[1];
    switch ($ext) {
//            case "png":
//                $imgs=imagecreatefrompng($img);
//                break;
        case "jpeg":
        case "jpg":
            $imgs = imagecreatefromjpeg($img);
            break;
        case "gif":
            $imgs = imagecreatefromgif($img);
            break;
        default :
            $imgs = imagecreatefrompng($img);
            break;
    }
//        if(in_array($cid,[41,42])){
//            imagecopy($imgs, $img_content, 223, 552, 0, 0,315,315);//核心函数：复制图片资源到另一图片资源中
//        }else{
    imagecopy($imgs, $img_content, 231, 560, 0, 0, 285, 285);//核心函数：复制图片资源到另一图片资源中
//        }

    //imagecopy($imgd,$imgw,$x,$y,0,0, $wwidth,$wheight);
    //$save="image".$dtype;

    //保存到服务器
    $f_file_name = $patch . $return_file;
    imagepng($imgs, $f_file_name); //保存
    imagedestroy($imgs);
    imagedestroy($thumb);//销毁图片资源
    return $return_file;

}

/**
 * 二图合二为一
 * @param $img
 * @param $avatarUrl
 * @param $patch
 * @return string
 */
function createShare2($img, $avatarUrl, $patch, $return_file, $cid = 0)
{
    $thumb = imagecreatetruecolor(285, 285);     //创建一个新的画布（缩放后的），从左上角开始填充透明背景
    list($src_w, $src_h) = getimagesize('.' . $avatarUrl);
    $img_content = imagecreatefrompng('.' . $avatarUrl);//获取图片资源
    imagecopyresampled($thumb, $img_content, 0, 0, 0, 0, 285, 285, $src_w, $src_h);//核心函数，改变图片大小
    $file_name = './upload/test/' . uniqid() . '.png';
    imagepng($thumb, $file_name);//将图片资源保存到qrcode_1.png中
    //2、将缩小的二维码合成到海报中
//    $img = '.'.ltrim($img,'.');
    $ename = getimagesize($img);
    $ename = explode('/', $ename['mime']);
    $ext = $ename[1];
    switch ($ext) {
//            case "png":
//                $imgs=imagecreatefrompng($img);
//                break;
        case "jpeg":
        case "jpg":
            $imgs = imagecreatefromjpeg($img);
            break;
        case "gif":
            $imgs = imagecreatefromgif($img);
            break;
        default :
            $imgs = imagecreatefrompng($img);
            break;
    }
//        if(in_array($cid,[41,42])){
//            imagecopy($imgs, $img_content, 223, 552, 0, 0,315,315);//核心函数：复制图片资源到另一图片资源中
//        }else{
    imagecopy($imgs, $img_content, 231, 830, 0, 0, 285, 285);//核心函数：复制图片资源到另一图片资源中
//        }

    //imagecopy($imgd,$imgw,$x,$y,0,0, $wwidth,$wheight);
    //$save="image".$dtype;

    //保存到服务器
    $f_file_name = $patch . $return_file;
    imagepng($imgs, $f_file_name); //保存
    imagedestroy($imgs);
    imagedestroy($thumb);//销毁图片资源
    return $return_file;

}

/**
 * 生成海报
 */
function createPoster($uid, $background, $QR, $filename)
{
    /**
     * 背景图
     * 头像
     * 昵称
     * 邀请码
     * 手机号
     * 云副业 轻创业 高收入
     * 二维码
     * 扫码加入云副业
     */
    $user = \think\facade\Db::name('user')->where('id', $uid)->find();
    $nickname = $user['nickname'];
    include_once app()->getRootPath() . 'extend/phpqrcode.php';
    // 根据商品ID生成二维码图
    $code = $QR;
    $config = array(
        'text' => array(
            array(
                'text' => $nickname,
                'left' => 252,
                'top' => 1570,
                'fontPath' => 'uploads/poster/simhei.ttf',     //字体文件
                'fontSize' => 45,             //字号
                'fontColor' => '38,36,36',       //字体颜色
                'angle' => 0,
            ), array(
                'text' => 'F' . $user['shareCode'],
                'left' => 254,
                'top' => 1631,
                'fontPath' => 'uploads/poster/simhei.ttf',     //字体文件
                'fontSize' => 34,             //字号
                'fontColor' => '100,100,100',       //字体颜色
                'angle' => 0,
            ), array(
                'text' => '邀请您加入云副业 开启新征程',
                'left' => 254,
                'top' => 1680,
                'fontPath' => 'uploads/poster/simhei.ttf',     //字体文件
                'fontSize' => 24,             //字号
                'fontColor' => '130,130,130',       //字体颜色
                'angle' => 0,
            ), array(
                'text' => '扫码加入云副业',
                'left' => 785,
                'top' => 1755,
                'fontPath' => 'uploads/poster/simhei.ttf',     //字体文件
                'fontSize' => 22,             //字号
                'fontColor' => '119,119,119',       //字体颜色
                'angle' => 0,
            )
        ),
        'image' => array(
            array(
                'url' => '/uploads/poster/logo.png',
                'left' => 108,
                'top' => 1523,
                'right' => 0,
                'stream' => 0,
                'bottom' => 0,
                'width' => 107,
                'height' => 107,
                'angle' => 0.5,
                'opacity' => 100
            ), array(
                'url' => '/uploads/poster/partner.png',
                'left' => 577,
                'top' => 1521,
                'right' => 0,
                'stream' => 0,
                'bottom' => 0,
                'width' => 140,
                'height' => 49,
                'opacity' => 100
            ), array(
                'url' => $code,
                'left' => 785,
                'top' => 1517,
                'right' => 0,
                'stream' => 0,
                'bottom' => 0,
                'width' => 209,
                'height' => 210,
                'opacity' => 100
            )
        ),
        'background' => ltrim($background, '/'),
    );

//        $filename = $PNG_TEMP_DIR . 'goods_' . $goods_id . '.png';

    //如果要看报什么错，可以先注释调这个header
//        if (empty($filename)) header("content-type: image/png");
    $imageDefault = array(
        'left' => 0,
        'top' => 0,
        'right' => 0,
        'bottom' => 0,
        'width' => 100,
        'height' => 100,
        'opacity' => 100
    );
    $textDefault = array(
        'text' => '',
        'left' => 0,
        'top' => 0,
        'fontSize' => 32,       //字号
        'fontColor' => '255,255,255', //字体颜色
        'angle' => 0,
    );
    $background = $config['background'];//海报最底层得背景
    //背景方法
    $backgroundInfo = getimagesize($background);
    $backgroundFun = 'imagecreatefrom' . image_type_to_extension($backgroundInfo[2], false);
    $background = $backgroundFun($background);
    $backgroundWidth = imagesx($background);  //背景宽度
    $backgroundHeight = imagesy($background);  //背景高度
    $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
    $color = imagecolorallocate($imageRes, 255, 255, 255);
    imagefill($imageRes, 0, 0, $color);
    // imageColorTransparent($imageRes, $color);  //颜色透明
    imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background));
    //处理了图片
    if (!empty($config['image'])) {
        foreach ($config['image'] as $key => $val) {
            $val = array_merge($imageDefault, $val);
            if (strpos($val['url'], 'ttp') > 0) {
                $info = getimagesize($val['url']);
            } else {
                $val['url'] = '.' . ltrim($val['url'], '.');
                $info = getimagesize($val['url']);
            }
            $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
            if ($val['stream']) {   //如果传的是字符串图像流
                $info = getimagesizefromstring($val['url']);
                $function = 'imagecreatefromstring';
            }
            $res = $function($val['url']);
            $resWidth = $info[0];
            $resHeight = $info[1];
            //建立画板 ，缩放图片至指定尺寸
            $canvas = imagecreatetruecolor($val['width'], $val['height']);
            imagefill($canvas, 0, 0, $color);
            //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
            imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
            $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left'];
            $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
            //放置图像
            imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']);//左，上，右，下，宽度，高度，透明度
        }
    }
    //处理文字
    if (!empty($config['text'])) {
        foreach ($config['text'] as $key => $val) {
            $val = array_merge($textDefault, $val);
            list($R, $G, $B) = explode(',', $val['fontColor']);
            $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
            $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
            $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
            imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
        }
    }
    //生成图片
    if (!empty($filename)) {
        $res = imagejpeg($imageRes, ltrim(ltrim($filename, '.'), '/'), 90); //保存到本地
        imagedestroy($imageRes);
        if (!$res) exception('网络错误，请稍后重试');
        return $filename;
    } else {
        imagejpeg($imageRes);     //在浏览器上显示
        imagedestroy($imageRes);
    }

}

/**
 * 生成二维码
 * @param $url
 * @param $QR
 * @return mixed
 */
function create_qr_code($url, $QR, $logo = FALSE, $cid = 0)
{
    include_once app()->getRootPath() . 'extend/phpqrcode.php';
    $value = $url; //二维码内容
    $errorCorrectionLevel = 'L';//容错级别
    if (in_array($cid, \think\facade\Db::table('fa_creditcard_product')->where('settlementType', 2)->column('id'))) {
        $matrixPointSize = 6.5;//生成图片大小
    } else {
        $matrixPointSize = 7.9;//生成图片大小
    }

    \think\facade\Log::write($matrixPointSize);
    //生成二维码图片
    QRcode::png($value, public_path() . $QR, $errorCorrectionLevel, $matrixPointSize, 2);
//        try{
//            if ($logo !== FALSE) {
//                $QR = imagecreatefromstring(file_get_contents(trim($QR,'/')));
//                $logo = imagecreatefromstring(file_get_contents($logo));
//                $QR_width = imagesx($QR);//二维码图片宽度
//                $QR_height = imagesy($QR);//二维码图片高度
//                $logo_width = imagesx($logo);//logo图片宽度
//                $logo_height = imagesy($logo);//logo图片高度
//                $logo_qr_width = $QR_width / 5;
//                $scale = $logo_width/$logo_qr_width;
//                $logo_qr_height = $logo_height/$scale;
//                $from_width = ($QR_width - $logo_qr_width) / 2;
//                //重新组合图片并调整大小
//                imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
//                    $logo_qr_height, $logo_width, $logo_height);
//            }
//        }catch (\Exception $e){
//            \exception($e->getMessage());
//        }

//        $logo = 'jb51.png';//准备好的logo图片
//        $QR = 'qrcode.png';//已经生成的原始二维码图


////输出图片
//        Header("Content-type: image/png");
//        ImagePng($QR);
    return $QR;
}

/**
 * 实名认证检测
 */
function naidcard($idCard, $idCardName)
{
    $ip = request()->ip();
    $ip = 'ip' . str_replace('.', '', $ip);
//		if(cache($ip) >= 5){
//			return ['code'=>0,'msg'=>'操作频繁，请明天再来','data'=>[]];
//		}
//		if(cache($ip) > 0){
//			cache($ip,cache($ip)+1);
//		}else{
//			cache($ip,1,86400);
//		}
    error_reporting(E_ALL || ~E_NOTICE);
    $host = "https://naidcard.market.alicloudapi.com";
    $path = "/nidCard";
    $method = "GET";

//    'naidcard' => [
//    'AppCode' => '709956ccf469455f9a4051b0bb2b6446',
//    'AppSecret' => 'ee4dd45fcaa951e6911f88dc950de550',
//    'AppKey' => '25079831',
//],
    $appcode = '709956ccf469455f9a4051b0bb2b6446';//开通服务后 买家中心-查看AppCode
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "idCard=$idCard&name=" . urlencode("$idCardName");

    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    if (1 == strpos("$" . $host, "https://")) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $out_put = curl_exec($curl);

    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    list($header, $body) = explode("\r\n\r\n", $out_put, 2);
    if ($httpCode == 200) {
        $dataJson = json_decode($body, true);
        if ($dataJson['status'] == '01') {
            return ['code' => 1, 'msg' => $dataJson['msg'], 'data' => $dataJson];
        } else {
            return ['code' => 0, 'msg' => $dataJson['msg'], 'data' => $dataJson];
        }
    } else {
        if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
            return ['code' => 0, 'msg' => '参数错误', 'data' => []];
        } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
            return ['code' => 0, 'msg' => 'AppCode错误', 'data' => []];
        } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
            return ['code' => 0, 'msg' => '请求的 Method、Path 或者环境错误', 'data' => []];
        } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
            return ['code' => 0, 'msg' => '服务未被授权（或URL和Path不正确）', 'data' => []];
        } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
            return ['code' => 0, 'msg' => '套餐包次数用完', 'data' => []];
        } elseif ($httpCode == 500) {
            return ['code' => 0, 'msg' => 'API网关错误', 'data' => []];
        } elseif ($httpCode == 0) {
            return ['code' => 0, 'msg' => 'URL错误', 'data' => []];
        } else {
            $headers = explode("\r\n", $header);
            $headList = array();
            foreach ($headers as $head) {
                $value = explode(':', $head);
                $headList[$value[0]] = $value[1];
            }
            return ['code' => 0, 'msg' => '参数名错误 或 其他错误:' . $headList['x-ca-error-message'], 'data' => $httpCode];
        }
    }
}

if ('cli' != PHP_SAPI) {
    if ($_SERVER['DOCUMENT_ROOT'] && (strlen($_SERVER['DOCUMENT_ROOT']) - 7) == strpos($_SERVER['DOCUMENT_ROOT'], '/public')) {
        //SCRIPT_FILENAME
        define('IS_SAFE_MODE', true);
    } else {
        define('IS_SAFE_MODE', false);
    }
} else {
    define('IS_SAFE_MODE', true);
}
function check_alipay($data)
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayTradeAppPayRequest.php';
    $alipayClient = new AopCertClient(getAlipayConfig());
    $appCertPath = root_path() . "data/alipay/appCertPublicKey_2021004181661289.crt";
    if (isset($data['fund_bill_list'])) {
        $data['fund_bill_list'] = htmlspecialchars_decode($data['fund_bill_list']);
    }
    return $alipayClient->rsaCheckV1($data, $appCertPath, $data['sign_type']);
}

function alipay_transfer($orderId, $amount, $account, $name)
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayFundTransUniTransferRequest.php';
    $alipayClient = new AopCertClient(getAlipayConfig());
    $alipayClient->isCheckAlipayPublicCert = true;
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.open.public.template.message.industry.modify
    //$request = new AlipayOpenPublicTemplateMessageIndustryModifyRequest();
    $request = new AlipayFundTransUniTransferRequest();
    $request->setBizContent("{" .
        "\"out_biz_no\":\"$orderId\"," .
        "\"trans_amount\":\"$amount\"," .
        "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," .
        "\"biz_scene\":\"DIRECT_TRANSFER\"," .
        "\"order_title\":\"云副业提现\"," .
        "\"payee_info\":{" .
        "\"identity\":\"$account\"," .
        "\"identity_type\":\"ALIPAY_LOGON_ID\"," .
        "\"name\":\"$name\"" .
        "    }," .
        "\"remark\":\"单笔转账\"," .
        "  }");
    $result = $alipayClient->execute($request);

    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $resultCode = $result->$responseNode->code;
//    dump($result->alipay_fund_trans_uni_transfer_response);
//    ["code"] => string(5) "10000"
//["msg"] => string(7) "Success"
//["order_id"] => string(32) "20241109020070011550170062031993"
//["out_biz_no"] => string(10) "1731132595"
//["pay_fund_order_id"] => string(32) "20241109020070011550170062031993"
//["status"] => string(7) "SUCCESS"
//["trans_date"] => string(19) "2024-11-09 14:09:56"
    if (!empty($resultCode) && $resultCode == 10000) {
        return ['code' => 0, 'order_id' => $result->$responseNode->order_id, 'trans_date' => $result->$responseNode->trans_date, 'msg' => $result->$responseNode->msg];
    } else {
        return ['code' => $result->$responseNode->code, 'msg' => $result->$responseNode->msg];

    }
}

function alipay_app_pay($orderNumber, $money, $title, $type = 'vip')
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayTradeAppPayRequest.php';
    $alipayClient = new AopCertClient(getAlipayConfig());
    $alipayClient->isCheckAlipayPublicCert = true;
    $request = new AlipayTradeAppPayRequest();
    // 设置订单绝对超时时间
//    $model['time_expire'] = "2016-12-31 10:05:00";
// 设置业务扩展参数
//    $extendParams = array();
//    $extendParams['sys_service_provider_id'] = "2088511833207846";
//    $extendParams['hb_fq_seller_percent'] = "100";
//    $extendParams['hb_fq_num'] = "3";
//    $extendParams['industry_reflux_info'] = "{\"scene_code\":\"metro_tradeorder\",\"channel\":\"xxxx\",\"scene_data\":{\"asset_name\":\"ALIPAY\"}}";
//    $extendParams['specified_seller_name'] = "XXX的跨境小铺";
//    $extendParams['royalty_freeze'] = "true";
//    $extendParams['card_type'] = "S0JP0000";
//    $model['extend_params'] = $extendParams;

// 设置商户订单号
    $model['out_trade_no'] = $orderNumber;
// 设置外部指定买家
//    $extUserInfo = array();
//    $extUserInfo['cert_type'] = "IDENTITY_CARD";
//    $extUserInfo['cert_no'] = "362334768769238881";
//    $extUserInfo['name'] = "李明";
//    $extUserInfo['mobile'] = "16587658765";
//    $extUserInfo['min_age'] = "18";
//    $extUserInfo['need_check_info'] = "F";
//    $extUserInfo['identity_hash'] = "27bfcd1dee4f22c8fe8a2374af9b660419d1361b1c207e9b41a754a113f38fcc";
//    $model['ext_user_info'] = $extUserInfo;
//
// 设置通知参数选项
    $model['query_options'][] = 'receipt_amount';
    $model['query_options'][] = 'buyer_pay_amount';
//
// 设置订单总金额
    $model['total_amount'] = $money;
// 设置订单标题
    $model['subject'] = $title;
// 设置产品码
    $model['product_code'] = 'QUICK_MSECURITY_PAY';
// 设置公用回传参数
    $model['passback_params'] = $type;
// 设置订单包含的商品列表信息
//    $goodsDetail = array();
//    $goodsDetail0 = array();
//    $goodsDetail0['goods_name'] = "ipad";
//    $goodsDetail0['alipay_goods_id'] = "20010001";
//    $goodsDetail0['quantity'] = 1;
//    $goodsDetail0['price'] = "2000";
//    $goodsDetail0['goods_id'] = "apple-01";
//    $goodsDetail0['goods_category'] = "34543238";
//    $goodsDetail0['categories_tree'] = "124868003|126232002|126252004";
//    $goodsDetail0['show_url'] = "http://www.alipay.com/xxx.jpg";
//    $goodsDetail[] = $goodsDetail0;
//    $model['goods_detail'] = $goodsDetail;
// 设置商户的原始订单号
//    $model['merchant_order_no'] = time();
    $request->setBizContent(json_encode($model, JSON_UNESCAPED_UNICODE));
    $request->setNotifyUrl((string)url('/api/notify/pay/alipay', [], false, true));
    return $alipayClient->sdkExecute($request);

}

function alipay_app_pre_pay($orderNumber, $money, $title, $type = 'vip')
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayFundAuthOrderAppFreezeRequest.php';
    $alipayClient = new AopCertClient(getAlipayConfig());
    $alipayClient->isCheckAlipayPublicCert = true;
    $request = new AlipayFundAuthOrderAppFreezeRequest();
    // 设置订单绝对超时时间
    // 设置后付费项目
//    $postPayments = array();
//    $postPayments0 = array();
//    $postPayments0['amount'] = $money;
//    $postPayments0['name'] = "租金";
//    $postPayments0['description'] = "2元/小时，99元封顶";
//    $postPayments[] = $postPayments0;
//    $model['post_payments'] = $postPayments;
// 设置订单标题
    $model['order_title'] = $title;

// 设置需要冻结的金额
    $model['amount'] = $money;

// 设置收款账户的支付宝用户号
//    $model['payee_user_id'] = "2088102000275795";
// 设置商户授权资金订单号
    $model['out_order_no'] = $orderNumber;
// 设置销售产品码
    $model['product_code'] = "PREAUTH_PAY";

// 设置收款账户的支付宝登录号（email或手机号）
//    $model['payee_logon_id'] = "159****5620";

// 设置无特殊需要请勿传入
//    $model['enable_pay_channels'] ='[{"payChannelType":"PCREDIT_PAY"},{"payChannelType":"MONEY_FUND"},{"payChannelType":"CREDITZHIMA"}]';// "[{\"payChannelType\":\"pcredit,moneyFund,debitCardExpress\"}]";
//    $model['enable_pay_channels'] ='[{"payChannelType":"PCREDIT_PAY"}]';// "[{\"payChannelType\":\"pcredit,moneyFund,debitCardExpress\"}]";

// 设置免押受理台模式
    $model['deposit_product_mode'] = "POSTPAY";
// 设置无特殊需要请勿传入
//    $model['identity_params'] = "{\"identity_hash\":\"acc2b92ffc5ed9b472faa19748f10045c30434132784f774b00216a56b8841c6\"}";

// 设置业务参数
//    $model['business_params'] = "{\"outRiskInfo\":\"{\"mcCreateTradeTime\":\"2022-03-11 12:46:09\",\"extraAccountCertnoLastSix\":\"000011\",\"mobileOperatingPlatform\":\"ios\",\"sysVersion\":\"15.4.2\",\"mcCreateTradeIp\":\"11.110.111.43\"}\"}";
// 设置预授权订单相对超时时间
    $model['timeout_express'] = "2d";
// 设置无特殊需要请勿传入
//    $model['disable_pay_channels'] = "[{\"payChannelType\":\"OPTIMIZED_MOTO\"},{\"payChannelType\":\"BIGAMOUNT_CREDIT_CARTOON\"}]";

// 设置商户本次资金操作的请求流水号
    $model['out_request_no'] = $orderNumber;

    $request->setBizContent(json_encode($model, JSON_UNESCAPED_UNICODE));
    $request->setNotifyUrl((string)url('/api/notify/pay/freeze', [], false, true));
    return $alipayClient->sdkExecute($request);

}

function wechat_app_pay($pay)
{
    $pay_param['out_trade_no'] = $pay['pay_sn'];
    $pay_param['trade_type'] = 'APP';
    $pay_param['notify_url'] = (string)url('/api/notify/pay/wechat', [], false, true);
//    if ($pay['user_id'] == 16006) {
//        $pay_param['total_fee'] = 10;
//    } else {
        $pay_param['total_fee'] = $pay['total_amount'] * 100;
//    }
    $pay_param['attach'] = $pay['type'];
    $pay_param['detail'] = '';// 保留
    $pay_param['body'] = $pay['title'];
    $pay_param['device_info'] = 'app';
    $WechatMchPay = new WechatMchPay('wx7c83e79f78fdfa10', '1697093647', 'qC04wNxXUFVv2eEItzWpdb8BSPMTkHln');
    $pay_result = $WechatMchPay->unifiedorder($pay_param);
    if ('fail' == strtolower($pay_result['return_code'])) {
        throw new Exception($pay_result['return_msg']);
    }
    if ('fail' == strtolower($pay_result['result_code'])) {
        throw new Exception($pay_result['err_code_des']);
    }

    return $WechatMchPay->appSign($pay_result['prepay_id'], $pay_result['nonce_str']);
}

function wechat_app_pay_refund($pay, $amount, $desc)
{
    $query['out_trade_no'] = $pay['pay_sn'];
    $query['out_refund_no'] = $pay['pay_sn'].'X'.$pay['action_no'];
    $query['total_fee'] = round($pay['api_amount']*100,0);
    $query['refund_fee'] = $amount*100;
    $query['refund_desc'] =$desc;
    $WechatMchPay = new WechatMchPay('wx7c83e79f78fdfa10', '1697093647', 'qC04wNxXUFVv2eEItzWpdb8BSPMTkHln');
    return $WechatMchPay->refund($query);
}

function wechat_transfer($trade_no, $amount, $openid, $real_name, $desc)
{
    $query['partner_trade_no'] = $trade_no; //商户订单号，需保持唯一性
    $query['openid'] = $openid; //商户appid下，某用户的openid
    $query['check_name'] = 'FORCE_CHECK'; //NO_CHECK：不校验真实姓名 FORCE_CHECK：强校验真实姓名（未实名认证的用户会校验失败，无法转账） OPTION_CHECK：针对已实名认证的用户才校验真实姓名（未实名认证用户不校验，可以转账成功）
    $query['re_user_name'] = $real_name; //收款用户真实姓名。 如果check_name设置为FORCE_CHECK或OPTION_CHECK，则必填用户真实姓名
    $query['amount'] = $amount * 100; //企业付款金额，单位为分  最低金额100分
    $query['desc'] = $desc; //企业付款操作说明信息。必填。
    $query['spbill_create_ip'] = request()->ip(); //企业付款操作说明信息。必填。
    $WechatMchPay = new WechatMchPay('wx7c83e79f78fdfa10', '1697093647', 'qC04wNxXUFVv2eEItzWpdb8BSPMTkHln');
    return $WechatMchPay->transfers($query);
}

function alipay_app_h5_pre_pay($orderNumber, $money, $title, $type = 'vip')
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayFundAuthOrderAppFreezeRequest.php';
    $alipayClient = new AopCertClient(getAlipayConfig());
    $request = new AlipayFundAuthOrderAppFreezeRequest();

// 设置订单标题
    $model['order_title'] = $title;
// 设置需要冻结的金额
    $model['amount'] = $money;
// 设置收款账户的支付宝用户号
//    $model['payee_user_id'] = "2088102000275795";

// 设置预授权订单相对超时时间
    $model['timeout_express'] = '2d';
// 设置商户授权资金订单号
    $model['out_order_no'] = $orderNumber;
// 设置销售产品码
    $model['product_code'] = 'PREAUTH_PAY';
// 设置免押受理台模式
    $model['deposit_product_mode'] = 'POSTPAY';

// 设置商户本次资金操作的请求流水号
    $model['out_request_no'] = $orderNumber;

    $request->setBizContent(json_encode($model, JSON_UNESCAPED_UNICODE));
    $request->setNotifyUrl((string)url('/api/notify/pay/freeze', [], false, true));
    if ('pos' == $type) {
        $request->setReturnUrl('https://web.yunfuye.com/#/pages/user/order');
    } else {
        $request->setReturnUrl('https://web.yunfuye.com/#/pages/user/task');
    }
    $request->setNotifyUrl((string)url('/api/notify/pay/freeze', [], false, true));
//    $response =  $alipayClient->sdkExecute($request);
    return $alipayClient->sdkExecute($request);
//    $info = $response->getBody();
//    dump($info);
    // 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
    $pageRedirectionData = $alipayClient->pageExecute($request, "POST");
// 如果需要返回GET请求，请使用
// $pageRedirectionData = $alipayClient->pageExecute($request, "GET");
    return $pageRedirectionData;


}

/**
 * 退款
 * @param $auth_no
 * @param $money
 * @param $title
 * @return void
 * @throws Exception
 */
function alipay_app_unfreeze_pay($pay, $money, $remark)
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayFundAuthOrderUnfreezeRequest.php';
    $alipayClient = new AopCertClient(getAlipayConfig());
    $request = new AlipayFundAuthOrderUnfreezeRequest();
// 设置支付宝资金授权订单号
    $model['auth_no'] = $pay['auth_no'];

// 设置解冻请求流水号
    $model['out_request_no'] = $pay['pay_sn'] . 'X' . $pay['action_no'];

// 设置本次操作解冻的金额
    $model['amount'] = $money;

// 设置商户对本次解冻操作的附言描述
    $model['remark'] = $remark;

// 设置解冻扩展信息
//    $model['extra_param'] = "{\"unfreezeBizInfo\": \"{\"bizComplete\":\"true\"}\"}";

    $request->setBizContent(json_encode($model, JSON_UNESCAPED_UNICODE));
// 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
    $responseResult = $alipayClient->execute($request);
    $responseApiName = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $response = $responseResult->$responseApiName;
    \think\facade\Log::write($response);
    if (!empty($response->code) && $response->code == 10000) {
        $pay['refund_money'] = $money;
        $pay['gmt_close'] = $response->gmt_trans;
        return true;
    } else {
        return false;
    }

}

/**
 * 预授权扣款
 * @param $auth_no
 * @param $money
 * @param $title
 * @return void
 * @throws Exception
 */
function alipay_app_freeze_pay(&$pay, $money, $remark)
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayTradePayRequest.php';
    $alipayClient = new AopCertClient(getAlipayConfig());
    $request = new AlipayTradePayRequest();

// 设置商户订单号
    $model['out_trade_no'] = $pay['pay_sn'] . 'P' . $pay['action_no'];

// 设置订单总金额
    $model['total_amount'] = $money;

// 设置订单标题
    $model['subject'] = $remark;

// 设置产品码
    $model['product_code'] = 'PREAUTH_PAY';

// 设置资金预授权单号
    $model['auth_no'] = $pay['auth_no'];

// 设置预授权确认模式
    $model['auth_confirm_mode'] = "COMPLETE";
    $request->setBizContent(json_encode($model, JSON_UNESCAPED_UNICODE));
// 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
    $responseResult = $alipayClient->execute($request);
    $responseApiName = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $response = $responseResult->$responseApiName;
    \think\facade\Log::write($responseResult);
    if (!empty($response->code) && $response->code == 10000) {
        $pay['api_pay_no'] = $response->trade_no;
        $pay['receipt_amount'] = $response->receipt_amount;
        return true;
    } else {
        return false;
    }

}

function alipay_app_refund($out_trade_no, $money, $reason, $out_request_no)
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayTradeRefundRequest.php';
    $alipayClient = new \AopCertClient(getAlipayConfig());
    $alipayClient->isCheckAlipayPublicCert = true;
    $request = new \AlipayTradeRefundRequest();
    // 设置商户订单号
    $model['out_trade_no'] = $out_trade_no;
// 设置支付宝交易号
//        $model['trade_no'] = "2014112611001004680073956707";

// 设置退款金额
    $model['refund_amount'] = $money;
// 设置退款原因说明
    $model['refund_reason'] = $reason;
// 设置退款请求号
    $model['out_request_no'] = $out_request_no;

    $request->setBizContent(json_encode($model, JSON_UNESCAPED_UNICODE));
// 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
    $result = $alipayClient->execute($request);
    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $response = $result->$responseNode;
    /**
     * object(stdClass)#154 (11) {
     * ["code"] =&gt; string(5) "10000"
     * ["msg"] =&gt; string(7) "Success"
     * ["buyer_logon_id"] =&gt; string(14) "lil***@163.com"
     * ["fund_change"] =&gt; string(1) "Y"
     * ["gmt_refund_pay"] =&gt; string(19) "2024-12-19 18:10:23"
     * ["out_trade_no"] =&gt; string(13) "9180772584647"
     * ["refund_detail_item_list"] =&gt; array(1) {
     * [0] =&gt; object(stdClass)#155 (2) {
     * ["amount"] =&gt; string(4) "0.01"
     * ["fund_channel"] =&gt; string(13) "ALIPAYACCOUNT"
     * }
     * }
     * ["refund_fee"] =&gt; string(4) "0.02"
     * ["send_back_fee"] =&gt; string(4) "0.01"
     * ["trade_no"] =&gt; string(28) "2024121822001474171408119874"
     * ["buyer_open_id"] =&gt; string(47) "0177AUyntXQuJMjY8gZdGsgRmlcCntiff8ZR0ljTZ9S0AQe"
     * }
     */

    return ['code' => $result->$responseNode->code, 'msg' => $result->$responseNode->msg];


}

function alipay_h5_pay($orderNumber, $money, $title, $type = 'vip')
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
//    require_once '../extend/aop/request/AlipayTradeAppPayRequest.php';
    require_once '../extend/aop/request/AlipayTradeWapPayRequest.php';
    $alipayClient = new AopCertClient(getAlipayConfig());
    $alipayClient->isCheckAlipayPublicCert = true;
    $request = new AlipayTradeWapPayRequest();
    // 设置订单绝对超时时间
//    $model['time_expire'] = "2016-12-31 10:05:00";
// 设置业务扩展参数
//    $extendParams = array();
//    $extendParams['sys_service_provider_id'] = "2088511833207846";
//    $extendParams['hb_fq_seller_percent'] = "100";
//    $extendParams['hb_fq_num'] = "3";
//    $extendParams['industry_reflux_info'] = "{\"scene_code\":\"metro_tradeorder\",\"channel\":\"xxxx\",\"scene_data\":{\"asset_name\":\"ALIPAY\"}}";
//    $extendParams['specified_seller_name'] = "XXX的跨境小铺";
//    $extendParams['royalty_freeze'] = "true";
//    $extendParams['card_type'] = "S0JP0000";
//    $model['extend_params'] = $extendParams;

// 设置商户订单号
    $model['out_trade_no'] = $orderNumber;
// 设置外部指定买家
//    $extUserInfo = array();
//    $extUserInfo['cert_type'] = "IDENTITY_CARD";
//    $extUserInfo['cert_no'] = "362334768769238881";
//    $extUserInfo['name'] = "李明";
//    $extUserInfo['mobile'] = "16587658765";
//    $extUserInfo['min_age'] = "18";
//    $extUserInfo['need_check_info'] = "F";
//    $extUserInfo['identity_hash'] = "27bfcd1dee4f22c8fe8a2374af9b660419d1361b1c207e9b41a754a113f38fcc";
//    $model['ext_user_info'] = $extUserInfo;
//
// 设置通知参数选项
//    $model['query_options'][] ='receipt_amount';
//    $model['query_options'][] ='buyer_pay_amount';
//
// 设置订单总金额
    $model['total_amount'] = $money;
// 设置订单标题
    $model['subject'] = $title;
// 设置产品码
    $model['product_code'] = 'QUICK_WAP_WAY';
// 设置公用回传参数
    $model['passback_params'] = $type;

// 设置商户的原始订单号
    $model['merchant_order_no'] = time();
// 设置订单包含的商品列表信息
//    $goodsDetail = array();
//    $goodsDetail0 = array();
//    $goodsDetail0['goods_name'] = "ipad";
//    $goodsDetail0['alipay_goods_id'] = "20010001";
//    $goodsDetail0['quantity'] = 1;
//    $goodsDetail0['price'] = "2000";
//    $goodsDetail0['goods_id'] = "apple-01";
//    $goodsDetail0['goods_category'] = "34543238";
//    $goodsDetail0['categories_tree'] = "124868003|126232002|126252004";
//    $goodsDetail0['show_url'] = "http://www.alipay.com/xxx.jpg";
//    $goodsDetail[] = $goodsDetail0;
//    $model['goods_detail'] = $goodsDetail;
// 设置商户的原始订单号
//    $model['merchant_order_no'] = time();
    $request->setBizContent(json_encode($model, JSON_UNESCAPED_UNICODE));
    $request->setNotifyUrl((string)url('/api/notify/pay/alipay', [], false, true));
    if ('pos' == $type) {
        $request->setReturnUrl('https://web.yunfuye.com/#/pages/user/order');
    } else {
        $request->setReturnUrl('https://web.yunfuye.com/#/pages/user/task');
    }

    // 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
    $pageRedirectionData = $alipayClient->pageExecute($request, "POST");
// 如果需要返回GET请求，请使用
// $pageRedirectionData = $alipayClient->pageExecute($request, "GET");
    return $pageRedirectionData;

}

function getAlipayConfig()
{

    $privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCbZ2SIsbDCutaxmt12iWQhKf1szMH9/jhEZAL2Z96HfPLZv6+vRoYyDd97yhnG6rRpI7nB7ABgv+8dtjcNyVp6HlMnvKvHxx9lJAaQ8+wPcVW2GQlZ5+k+kC8hac1SPxXtWb44qZy9jxW5rrBnw/sE+US9+wKHnt7sUJrISu9wnTtOADXtXQEgUUV6rYar/gJ3XcR5oBbWkgt/mQX2ffm3Ks8XedCdBe3T+5umXQ5QhG3hjh9ktSQ/+8afqD38OQdD6oVat/Taa0vPouHh9QP1XHjHcq3/QiyF1cza+D7KJ1iUcnVnDbSfL5PuCJOME4EpfEFUzcFwuXstnCadgKBxAgMBAAECggEAMA9tvAiYDeESfKLUUtBysv71bSx14kM4y43SjLnazDQMNuNdReudnOVFdFcwWaBEYy+1Rw/hngo9vQaZSB45aQLv3J4w0fv27aSSk0mce7olM8fSaIecTsjwinjaEtGHynuypHtwCf+yTFaGH9EwVH1ykP6L7b1oW9UhyUfDfSPlHGBsNJhGaGyZwtOQzz8Q3z2N1MhibgnE1xmNo/1mKXnfPulckaDV11p8Fwod221qOmULzkPzGFbQIS0haeP2P68YLGLFdn4g9WTQZHxbmKM6L6VIAo0hh8En1rvMmDi7zIjVVxWbzaGi10cM5Ex5dQB1tnpNgYninZ+t4D/JQQKBgQD10D4UIvd+w0zjjhs1UCvNWIQMKkHq3PojEiOq5fMtZ7QEU9E7CXyMRufNhBsyW0A9lu+EFCuBpCSjhKZsZJXZInBoDjHp6GUTAGP4HY6QEwoLrWzt0rpuysxyuQEqNFkcJWBUouXjTZ3zpt7KgYcBSCJaBom9xy4N7mJlkPUl3QKBgQCh2AYHDRSvXtk1Uc2JDM4DOaXEz2pohX0yB1I7nqzsqMnKzg8APjxw9U1boSSlRc8oDwL31LV40pVMvJBPtchDJx5d0sbKNaEU8bsGjIMmEOtF6PiraT6VMzJhw1cVJALUiuankAdyS2MJtTqbeknWaFMMdBtxze3LBhsK3S8NpQKBgEBodBuqndblLXxie9aYTyHbE55sZCE6DYCq/BWHcxRum8iWfbhOYAgRfCNpfgbPyiFZLyEYd93cOI1v8HtuT6U5VOKu9X0om3NDIu6cMAKoOnWc13HpSVhGYxOcTiXU2ZR6ZqdGl53bdIunKbE+BzXaxMV5+RV03yhfUgDy3okxAoGAaS255RU0LzBl2sf52ipPLDtnprrhPWIbVcr6PzLE0Nx0n+9AQnkv0H0qs/TKmvn+QdtXo3ZCJW49huw4oQTTTAj9LB5SAJHPyIu8buocRT3TmNBp4wP3nwDxqiVHz75idHx8n8Lzg+zIRUPY/bgAim2sIzjFqTUaZ8nlAy9xZ90CgYEAjPseDQE57ZD7qG1krSQIUWCtILWMoDRRbIqFyIvtTkRebeQZDtWgdz9gGkVXbI8I+Q2brPDlBncRpckHsq3KjbpiMMQSYv/AwOwuB6BICFYv0rKKcEx1L5wn8kmBsJ4UENdAYzqxMm57CD7M8VtCl7KCyfXAs93IeP3q2KhMnlY=";
    $appCertPath = root_path() . "data/alipay/appCertPublicKey_2021004181661289.crt";
    $alipayCertPath = root_path() . "data/alipay/alipayCertPublicKey_RSA2.crt";
    $rootCertPath = root_path() . "data/alipay/alipayRootCert.crt";

    $alipayConfig = new AlipayConfig();
    $alipayConfig->setPrivateKey($privateKey);
    $alipayConfig->setServerUrl("https://openapi.alipay.com/gateway.do");
    $alipayConfig->setAppId("2021004181661289");
    $alipayConfig->setCharset("UTF-8");
    $alipayConfig->setSignType("RSA2");
    $alipayConfig->setEncryptKey("");
    $alipayConfig->setFormat("json");

    $alipayConfig->setRootCertPath($rootCertPath);
    $alipayConfig->setAlipayPublicCertPath($alipayCertPath);
    $alipayConfig->setAppCertPath($appCertPath);
    return $alipayConfig;
}

function pay2($orderNumber, $money, $title)
{
    require_once '../extend/aop/AopClient.php';
    require_once '../extend/aop/AopCertClient.php';
    require_once '../extend/aop/AopCertification.php';
    require_once '../extend/aop/AlipayConfig.php';
    require_once '../extend/aop/request/AlipayTradeAppPayRequest.php';
    require_once('../extend/aop/AopCertClient.php');
    $aop = new AopCertClient();


    $appCertPath = "./alipay/appCertPublicKey_2021004181661289.crt";
    $alipayCertPath = root_path() . "data/alipay/alipayCertPublicKey_RSA2.crt";
    $rootCertPath = "./alipay/alipayRootCert.crt";

    $privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCbZ2SIsbDCutaxmt12iWQhKf1szMH9/jhEZAL2Z96HfPLZv6+vRoYyDd97yhnG6rRpI7nB7ABgv+8dtjcNyVp6HlMnvKvHxx9lJAaQ8+wPcVW2GQlZ5+k+kC8hac1SPxXtWb44qZy9jxW5rrBnw/sE+US9+wKHnt7sUJrISu9wnTtOADXtXQEgUUV6rYar/gJ3XcR5oBbWkgt/mQX2ffm3Ks8XedCdBe3T+5umXQ5QhG3hjh9ktSQ/+8afqD38OQdD6oVat/Taa0vPouHh9QP1XHjHcq3/QiyF1cza+D7KJ1iUcnVnDbSfL5PuCJOME4EpfEFUzcFwuXstnCadgKBxAgMBAAECggEAMA9tvAiYDeESfKLUUtBysv71bSx14kM4y43SjLnazDQMNuNdReudnOVFdFcwWaBEYy+1Rw/hngo9vQaZSB45aQLv3J4w0fv27aSSk0mce7olM8fSaIecTsjwinjaEtGHynuypHtwCf+yTFaGH9EwVH1ykP6L7b1oW9UhyUfDfSPlHGBsNJhGaGyZwtOQzz8Q3z2N1MhibgnE1xmNo/1mKXnfPulckaDV11p8Fwod221qOmULzkPzGFbQIS0haeP2P68YLGLFdn4g9WTQZHxbmKM6L6VIAo0hh8En1rvMmDi7zIjVVxWbzaGi10cM5Ex5dQB1tnpNgYninZ+t4D/JQQKBgQD10D4UIvd+w0zjjhs1UCvNWIQMKkHq3PojEiOq5fMtZ7QEU9E7CXyMRufNhBsyW0A9lu+EFCuBpCSjhKZsZJXZInBoDjHp6GUTAGP4HY6QEwoLrWzt0rpuysxyuQEqNFkcJWBUouXjTZ3zpt7KgYcBSCJaBom9xy4N7mJlkPUl3QKBgQCh2AYHDRSvXtk1Uc2JDM4DOaXEz2pohX0yB1I7nqzsqMnKzg8APjxw9U1boSSlRc8oDwL31LV40pVMvJBPtchDJx5d0sbKNaEU8bsGjIMmEOtF6PiraT6VMzJhw1cVJALUiuankAdyS2MJtTqbeknWaFMMdBtxze3LBhsK3S8NpQKBgEBodBuqndblLXxie9aYTyHbE55sZCE6DYCq/BWHcxRum8iWfbhOYAgRfCNpfgbPyiFZLyEYd93cOI1v8HtuT6U5VOKu9X0om3NDIu6cMAKoOnWc13HpSVhGYxOcTiXU2ZR6ZqdGl53bdIunKbE+BzXaxMV5+RV03yhfUgDy3okxAoGAaS255RU0LzBl2sf52ipPLDtnprrhPWIbVcr6PzLE0Nx0n+9AQnkv0H0qs/TKmvn+QdtXo3ZCJW49huw4oQTTTAj9LB5SAJHPyIu8buocRT3TmNBp4wP3nwDxqiVHz75idHx8n8Lzg+zIRUPY/bgAim2sIzjFqTUaZ8nlAy9xZ90CgYEAjPseDQE57ZD7qG1krSQIUWCtILWMoDRRbIqFyIvtTkRebeQZDtWgdz9gGkVXbI8I+Q2brPDlBncRpckHsq3KjbpiMMQSYv/AwOwuB6BICFYv0rKKcEx1L5wn8kmBsJ4UENdAYzqxMm57CD7M8VtCl7KCyfXAs93IeP3q2KhMnlY=";
//    $alipayPublicKey = $aop->getPublicKey($alipayCertPath);;
//    dump($alipayPublicKey);
    $alipayConfig = new AlipayConfig();
    $alipayConfig->setServerUrl("https://openapi.alipay.com/gateway.do");
//    $alipayConfig->setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");.
    $alipayConfig->setAppId("2021004181661289");
    $alipayConfig->setPrivateKey($privateKey);
    $alipayConfig->setFormat("json");
    $alipayConfig->setAlipayPublicCertPath($alipayCertPath);
    $alipayConfig->setCharset("UTF-8");
    $alipayConfig->setSignType("RSA2");
    $alipayClient = new AopClient($alipayConfig);
    $request = new AlipayTradeAppPayRequest();
    $params = ['out_trade_no' => time(), 'total_amount' => 0.01, 'subject' => '开通会员'];
    $bizcontent = "{"
        . "\"subject\": \"合伙人直升-$title\","
        . "\"out_trade_no\": \"$orderNumber\","
        . "\"total_amount\": \"$money\","
        . "\"product_code\":\"QUICK_MSECURITY_PAY\""
        . "}";
    \think\facade\Log::write($bizcontent);
    $request->setBizContent($bizcontent);
    $orderStr = $alipayClient->sdkExecute($request);
    return $orderStr;

}

function pay($orderNumber, $money, $title)
{
    require_once('../extend/aop/request/AlipayTradeAppPayRequest.php');
    require_once('../extend/aop/AopCertClient.php');
    $c = new AopCertClient();
    $appCertPath = "./alipay/appCertPublicKey_2021004181661289.crt";
    $alipayCertPath = "./alipay/alipayCertPublicKey_RSA2.crt";
    $rootCertPath = "./alipay/alipayRootCert.crt";


    // 支付宝公钥
//    $config['alipay_public_path'] = realpath(app()->getRootPath() . 'data/alipay/alipayCertPublicKey_RSA2.crt');
//    //应用公钥证书完整内容（新版资金类接口转 app_cert_sn）
//    $config['app_public_path'] = realpath(app()->getRootPath() . 'data/alipay/appCertPublicKey_' . $config['appid'] . '.crt');
//    //应用公钥证书完整内容（新版资金类接口转 app_cert_sn）
//    $config['alipay_root_path'] = realpath(app()->getRootPath() . 'data/alipay/alipayRootCert.crt');


    $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
    $c->appId = "2021004181661289";
    $c->rsaPrivateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCbZ2SIsbDCutaxmt12iWQhKf1szMH9/jhEZAL2Z96HfPLZv6+vRoYyDd97yhnG6rRpI7nB7ABgv+8dtjcNyVp6HlMnvKvHxx9lJAaQ8+wPcVW2GQlZ5+k+kC8hac1SPxXtWb44qZy9jxW5rrBnw/sE+US9+wKHnt7sUJrISu9wnTtOADXtXQEgUUV6rYar/gJ3XcR5oBbWkgt/mQX2ffm3Ks8XedCdBe3T+5umXQ5QhG3hjh9ktSQ/+8afqD38OQdD6oVat/Taa0vPouHh9QP1XHjHcq3/QiyF1cza+D7KJ1iUcnVnDbSfL5PuCJOME4EpfEFUzcFwuXstnCadgKBxAgMBAAECggEAMA9tvAiYDeESfKLUUtBysv71bSx14kM4y43SjLnazDQMNuNdReudnOVFdFcwWaBEYy+1Rw/hngo9vQaZSB45aQLv3J4w0fv27aSSk0mce7olM8fSaIecTsjwinjaEtGHynuypHtwCf+yTFaGH9EwVH1ykP6L7b1oW9UhyUfDfSPlHGBsNJhGaGyZwtOQzz8Q3z2N1MhibgnE1xmNo/1mKXnfPulckaDV11p8Fwod221qOmULzkPzGFbQIS0haeP2P68YLGLFdn4g9WTQZHxbmKM6L6VIAo0hh8En1rvMmDi7zIjVVxWbzaGi10cM5Ex5dQB1tnpNgYninZ+t4D/JQQKBgQD10D4UIvd+w0zjjhs1UCvNWIQMKkHq3PojEiOq5fMtZ7QEU9E7CXyMRufNhBsyW0A9lu+EFCuBpCSjhKZsZJXZInBoDjHp6GUTAGP4HY6QEwoLrWzt0rpuysxyuQEqNFkcJWBUouXjTZ3zpt7KgYcBSCJaBom9xy4N7mJlkPUl3QKBgQCh2AYHDRSvXtk1Uc2JDM4DOaXEz2pohX0yB1I7nqzsqMnKzg8APjxw9U1boSSlRc8oDwL31LV40pVMvJBPtchDJx5d0sbKNaEU8bsGjIMmEOtF6PiraT6VMzJhw1cVJALUiuankAdyS2MJtTqbeknWaFMMdBtxze3LBhsK3S8NpQKBgEBodBuqndblLXxie9aYTyHbE55sZCE6DYCq/BWHcxRum8iWfbhOYAgRfCNpfgbPyiFZLyEYd93cOI1v8HtuT6U5VOKu9X0om3NDIu6cMAKoOnWc13HpSVhGYxOcTiXU2ZR6ZqdGl53bdIunKbE+BzXaxMV5+RV03yhfUgDy3okxAoGAaS255RU0LzBl2sf52ipPLDtnprrhPWIbVcr6PzLE0Nx0n+9AQnkv0H0qs/TKmvn+QdtXo3ZCJW49huw4oQTTTAj9LB5SAJHPyIu8buocRT3TmNBp4wP3nwDxqiVHz75idHx8n8Lzg+zIRUPY/bgAim2sIzjFqTUaZ8nlAy9xZ90CgYEAjPseDQE57ZD7qG1krSQIUWCtILWMoDRRbIqFyIvtTkRebeQZDtWgdz9gGkVXbI8I+Q2brPDlBncRpckHsq3KjbpiMMQSYv/AwOwuB6BICFYv0rKKcEx1L5wn8kmBsJ4UENdAYzqxMm57CD7M8VtCl7KCyfXAs93IeP3q2KhMnlY=';
    $c->format = "json";
    $c->charset = "UTF-8";
    $c->signType = "RSA2";

//调用getPublicKey从支付宝公钥证书中提取公钥
    $c->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
    $c->isCheckAlipayPublicCert = true;
//调用getCertSN获取证书序列号
    $c->appCertSN = $c->getCertSN($appCertPath);
//调用getRootCertSN获取支付宝根证书序列号
    $c->alipayRootCertSN = $c->getRootCertSN($rootCertPath);

//        $aop = new AopClient;
//        $aop->gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
//        $aop->appId = " 2018080360961023";
//        $aop->rsaPrivateKey ='MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCbsO5pQdZuh+ueh3NVlxU/ZOI6qtYM0j5WN0JKIZjz2gEYX78gtIDim64ixLmjKr8AycqLhlXw5FCiRvAWZsseoxVaocFQyqDQ1XtBVt9FdVzm6mttE59oR+rIp58X13ySSXppU+d2gFxlf7CH4CHiv5wkfAOyriRiZSvhglsxQrG7bdOe5dCMjuAOwLeF9XdYnLPp6Uk4rKKkxxumxzonprt/RMVCf6qhhfqLoG1xm8B79ZFp4vd4ydbqS1tMnoAp2Z3NXZgWYPLqeSqGzvRxtNgLSvoSQxO8+mY+oX0m4bvm9Mu3URU2AgH1QURRj6ePmPw+8I8levs5ctjfjdAVAgMBAAECggEAUH0K9B2WVvQrynwqExCVan2kO0JAgMZcdcQBoEN4SHDm6gvtymGm1AA56T2c3w7lSeoIrVMYsP3H9e0Ih/xCfCdBjeZcA4GN3AjRvLjFmqoPCk4clXp0ibvMVEncBL5hZ1tXToaS/f9kRRDbWZN00T3P4ki+vKwsoTW+lsoGjRMnP3kiCJYbE9CdHexa75Gj10UrP7rvyM15oF/zBa8Pul7uZw8hW4xilu6BrIHf8mx1xeVpDelG7ES3Bk9vetZUWwPvgiSt1JutGy0pfvB7NR6+yTKgb6OXPIx3grkSpC9DDkiQzXZxEEhX1SxOUnbFA9nCy4nmgfi6mcoNgomDoQKBgQDdLVI7R4GQqnEn+UIZONqkr14lmHtZaJBRQnm7cs6y3eyhzxc8Z0MpT+7XHXXLjXBzqlifbDhkBDMd1SqzXvFQuvf5p8Qj0fdq9+HcuAmyogfiAr9X3NFf1tikOYI4DTiz86/GSAJkBS6yg4fde8LGUAosfak+IUA2NHVGL2w8XQKBgQC0NCj1IxD00QEg06Y4PLwENo3OLlLSjRK2DzLWLOXcxY4PGE8E3ZSiuIP6z1iH4burGRzdxssNZTFSN4aho8/XsSEECaQvBe/DVIkb5JeO4k0ZwgYEw+6rhLlX0i0YKeIouTSpgpC/wMD+erUD+846j7ZLJ62IIUHj9PHKiVTnGQKBgE0ZKEoLsgl4sHsrszPRkr3Hd70JOy4+edgpoP+LlKvbGkqJQuNGZ6319B6+YTp0clePcNcZxUpwAFWM4hamqN3oXtqC9ac64NFD2VK0QIUpYDATnxmEmuOao+gTN+ZMDZEFCCfJIDQ3bkDCAtFc+9dfPTynDSDgPF7oyFyP2V3tAoGAAM7zGBZuLwr4/FK2vi3XkhVEkZY3nOYxHUv4KGnPJixktMChKh5sWkaFoQxpE0L5+oyESqJnqsm3bOz+157KgeczhLceW2+lYbTxYISoAWYWfnUWXdMbMP3JbxFsTl1xvEkIaXJCf/m3Y+zc/wWUKUMXyEKHTsMHbqRcqVHwZZECgYBl80PnbIik1+9crJLBknPH48RTRiRQr+3+PDGWtv90u0M5/aY0WMCxvEkvNMG1Btxg0h77uNx8fLtWvmlDVAwfToQ13/nhYQ6xXq1l4NEph6pJkXZAjrmmEh7FipdDA3C35Y3WTR3XOn1XKfUU35ozAxfcYic4TbbbNiUvYy86Aw==';        $aop->format = "json";
//        $aop->charset = "UTF-8";
//        $aop->signType = "RSA2";
//        $aop->alipayrsaPublicKey ='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjjU+81eo8KhtsKy7bysuuZqfQ3zDbyIju+seJHAnQ7KqxJzso6U/eq2p8aIU74nYdVptfVPcMlt3trMrSkFVirRRvqjElDEhNffU+a0aSR0hus4GYi2iiHDpfV+75M14gNGwXFcWUXbpmXng2qDo3FXL2B+yrM7Iwzvkc7oOhOWrGaVu/uuyXrF3+MfNxYdGfx0BkgDlSPMw5AuwMLspWiaqF/8T/2LaVrTEf7x1tYNLikisR18TDqWa8AowPQW0rS+7TxoQsCEduJu9oEmoRL+QntpIm8gZXdL+opEdyatAy8gvMKH3wDS58wVwYGErjbJRJ+ts3VCnaXFJ7jut/QIDAQAB';
    //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
    $request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数
    $bizcontent = "{"
        . "\"subject\": \"合伙人直升-$title\","
        . "\"out_trade_no\": \"$orderNumber\","
        . "\"total_amount\": \"$money\","
        . "\"product_code\":\"QUICK_MSECURITY_PAY\""
        . "}";
    $request->setNotifyUrl((string)url('api/service.Pay/alipay', [], false, true));
    $request->setBizContent($bizcontent);
//这里和普通的接口调用不同，使用的是sdkExecute

    $response = $c->sdkExecute($request);
    $a = str_replace('&amp', '', $response);

//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
    return $response;//就是orderString 可以直接给客户端请求，无需再做处理。
}

/**
 * 取汉字的第一个字的首字母
 * @param string $str
 * @return string|null
 */
function get_first_char($str)
{
    if (empty($str)) {
        return '';
    }

    $fir = $fchar = ord($str[0]);
    if ($fchar >= ord('A') && $fchar <= ord('z')) {
        return strtoupper($str[0]);
    }

    $s1 = @iconv('UTF-8', 'gb2312', $str);
    $s2 = @iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    if (!isset($s[0]) || !isset($s[1])) {
        return '';
    }

    $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;

    if (is_numeric($str)) {
        return $str;
    }

    if (($asc >= -20319 && $asc <= -20284) || $fir == 'A') {
        return 'A';
    }
    if (($asc >= -20283 && $asc <= -19776) || $fir == 'B') {
        return 'B';
    }
    if (($asc >= -19775 && $asc <= -19219) || $fir == 'C') {
        return 'C';
    }
    if (($asc >= -19218 && $asc <= -18711) || $fir == 'D') {
        return 'D';
    }
    if (($asc >= -18710 && $asc <= -18527) || $fir == 'E') {
        return 'E';
    }
    if (($asc >= -18526 && $asc <= -18240) || $fir == 'F') {
        return 'F';
    }
    if (($asc >= -18239 && $asc <= -17923) || $fir == 'G') {
        return 'G';
    }
    if (($asc >= -17922 && $asc <= -17418) || $fir == 'H') {
        return 'H';
    }
    if (($asc >= -17417 && $asc <= -16475) || $fir == 'J') {
        return 'J';
    }
    if (($asc >= -16474 && $asc <= -16213) || $fir == 'K') {
        return 'K';
    }
    if (($asc >= -16212 && $asc <= -15641) || $fir == 'L') {
        return 'L';
    }
    if (($asc >= -15640 && $asc <= -15166) || $fir == 'M') {
        return 'M';
    }
    if (($asc >= -15165 && $asc <= -14923) || $fir == 'N') {
        return 'N';
    }
    if (($asc >= -14922 && $asc <= -14915) || $fir == 'O') {
        return 'O';
    }
    if (($asc >= -14914 && $asc <= -14631) || $fir == 'P') {
        return 'P';
    }
    if (($asc >= -14630 && $asc <= -14150) || $fir == 'Q') {
        return 'Q';
    }
    if (($asc >= -14149 && $asc <= -14091) || $fir == 'R') {
        return 'R';
    }
    if (($asc >= -14090 && $asc <= -13319) || $fir == 'S') {
        return 'S';
    }
    if (($asc >= -13318 && $asc <= -12839) || $fir == 'T') {
        return 'T';
    }
    if (($asc >= -12838 && $asc <= -12557) || $fir == 'W') {
        return 'W';
    }
    if (($asc >= -12556 && $asc <= -11848) || $fir == 'X') {
        return 'X';
    }
    if (($asc >= -11847 && $asc <= -11056) || $fir == 'Y') {
        return 'Y';
    }
    if (($asc >= -11055 && $asc <= -10247) || $fir == 'Z') {
        return 'Z';
    }

    return '';
}

/**
 * 获取语言变量值
 * @param string $name 语言变量名
 * @param array $vars 动态变量值
 * @param string $lang 语言
 * @return mixed
 */
function lang(string $name, array $vars = [], string $lang = '')
{

    if (LangThink::has($name)) {
        return LangThink::get($name, $vars, $lang);
    } else {
//			$module =request()->auth_module;
        if (!$lang) {
            $lang = app('lang')->getLangSet();
        }
        $lang = str_replace('-', '_', $lang);
        $data = LangModel::where('name', $name)->cache(60)->where('status', 1)->find();
        if (!$data) {
            $insert['name'] = $name;
            $insert['zh_cn'] = $name;
            $insert[$lang] = $name;
            $data = LangModel::create($insert);
        }
        $value = $data[$lang];
        // 变量解析
        if (!empty($vars) && is_array($vars)) {
            /**
             * Notes:
             * 为了检测的方便，数字索引的判断仅仅是参数数组的第一个元素的key为数字0
             * 数字索引采用的是系统的 sprintf 函数替换，用法请参考 sprintf 函数
             */
            if (key($vars) === 0) {
                // 数字索引解析
                array_unshift($vars, $value);
                $value = call_user_func_array('sprintf', $vars);
            } else {
                // 关联索引解析
                $replace = array_keys($vars);
                foreach ($replace as &$v) {
                    $v = "{:{$v}}";
                }
                $value = str_replace($replace, $vars, $value);
            }
        }

        return $value;
    }
}

/**
 * 过滤sql与php文件操作的关键字
 * @param string $string
 * @return string
 * @author zyb <zyb_icanplay@163.com>
 */
//if(!(filter_keyword($data['username'])===$data['username'])){
//				return WPreturn("用户名不合法", -1);
//			}


function filter_keyword($string)
{
    $keyword = 'select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|>|<|union|into|load_file|script|Script|outfile|and|execute|count|chr|mid|master|truncate|char|declare|create|or|=|%20';
    $arr = explode('|', $keyword);
    $result = str_ireplace($arr, '', $string);
    return $result;
}

function search_high_keyword($content)
{
    $keyword = request()->param('keyword');
    return str_replace($keyword, '<span style="color: red">' . $keyword . '</span>', $content);
}


function show_stock($stock)
{
    //库存大于100，显示“库存非常多”、小于100、大于30，显示“库存很多”、小于30、大于10，显示“库存一般”、小于10，显示“库存少量
    if ($stock > 100) {
        return '非常多';
    } elseif ($stock > 30) {
        return '很多';
    } elseif ($stock > 10) {
        return '一般';
    } else {
        return '少量';
    }
}

/**
 * 获取表field
 * @param $name
 * @return array
 */
function db_get_fields($name): array
{
    $arr = \think\facade\Db::query('SHOW COLUMNS FROM `' . Config::get('database.connections.mysql.prefix') . Str::snake($name) . '`');
    $re = [];
    foreach ($arr as $item) {
        $re[] = $item['Field'];
    }
    return $re;
}

function filter_script($str)
{
    $str = preg_replace("@<script(.*?)</script>@is", "", $str);
    $str = preg_replace("@<iframe(.*?)</iframe>@is", "", $str);
    $str = preg_replace("@<style(.*?)</style>@is", "", $str);
//		$str = preg_replace("@<(.*?)>@is", "", $str);
    //# 代表换行
    $str = str_replace("#", "<br>", $str);
    return $str;
}


function str_img($value)
{
    if (false !== strpos($value, '<img src="/ueditor/php/upload/image')) {
        $value = str_replace('<img src="/ueditor/php/upload/image', '<img src="' . request()->domain() . '/ueditor/php/upload/image', $value);
        return str_img($value);
    } else {
        return $value;
    }
}


function image_get_url($id, $preview = 'preview')
{
    return \app\file\event\Image::getUrl($id, $preview);
}

function picture_get_url($id, $preview = 'preview')
{
    return \app\file\event\Image::getUrl($id, $preview);
}

function is_weixin()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'],
            'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

/**
 * 取得根域名
 * @param string $domain 域名
 * @return string 返回根域名
 * @author  : 微尘 <yicmf@qq.com>
 * @datetime: 2019/3/16 11:30
 */
function get_url_root_domain($domain)
{
    $domain_postfix_cn_array = ["com", "net", "org", "gov", "edu", "com.cn", "cn", 'cc', 'co', 'vip', 'shop'];
    $array_domain = explode(".", $domain);
    $array_num = count($array_domain) - 1;
    if ($array_domain[$array_num] == 'cn') {
        if (in_array($array_domain[$array_num - 1], $domain_postfix_cn_array)) {
            $root_domain = $array_domain[$array_num - 2] . "." . $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
        } else {
            $root_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
        }
    } else {
        $root_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
    }
    return $root_domain;
}

function create_guid()
{
    $uid = uniqid("", true);
    $data = 'card';
    $data .= $_SERVER ['REQUEST_TIME'];    // 请求那一刻的时间戳
    $data .= $_SERVER ['HTTP_USER_AGENT'];    // 获取访问者在用什么操作系统
    $data .= $_SERVER ['SERVER_ADDR'];        // 服务器IP
    $data .= $_SERVER ['SERVER_PORT'];        // 端口号
    $data .= $_SERVER ['REMOTE_ADDR'];        // 远程IP
    $data .= $_SERVER ['REMOTE_PORT'];        // 端口信息
    $hash = strtoupper(hash('ripemd128', $uid . md5($data)));
    return substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
}

function tencent_captcha_check($param)
{
    if (Config::get('setting.tencent_captcha_open')) {
        try {
            // 腾讯安全验证
            $params = [
                "aid" => Config::get('setting.tencent_captcha_appid'),
                "AppSecretKey" => Config::get('setting.tencent_captcha_secret_key'),
                "Ticket" => $param['ticket'],
                "Randstr" => $param['randstr'],
                "UserIP" => request()->ip()
            ];
            $params = http_build_query($params);
            $result = \yicmf\tools\HttpService::post('https://ssl.captcha.qq.com/ticket/verify', $params);
            $data = json_decode($result['content'], true);
        } catch (\Exception $e) {
            $data['response'] = 0;
            $data['err_msg'] = $e->getMessage();
        }
    } else {
        $data['response'] = 1;
        $data['err_msg'] = '未开通';
    }
    return $data;
}

function randNickname()
{
    $tou = ['快乐', '冷静', '醉熏', '潇洒', '糊涂', '积极', '冷酷', '深情', '粗暴', '温柔', '可爱', '愉快', '义气', '认真', '威武', '帅气', '传统', '潇洒', '漂亮', '自然', '专一', '听话', '昏睡', '狂野', '等待', '搞怪', '幽默', '魁梧', '活泼', '开心', '高兴', '超帅', '留胡子', '坦率', '直率', '轻松', '痴情', '完美', '精明', '无聊', '有魅力', '丰富', '繁荣', '饱满', '炙热', '暴躁', '碧蓝', '俊逸', '英勇', '健忘', '故意', '无心', '土豪', '朴实', '兴奋', '幸福', '淡定', '不安', '阔达', '孤独', '独特', '疯狂', '时尚', '落后', '风趣', '忧伤', '大胆', '爱笑', '矮小', '健康', '合适', '玩命', '沉默', '斯文', '香蕉', '苹果', '鲤鱼', '鳗鱼', '任性', '细心', '粗心', '大意', '甜甜', '酷酷', '健壮', '英俊', '霸气', '阳光', '默默', '大力', '孝顺', '忧虑', '着急', '紧张', '善良', '凶狠', '害怕', '重要', '危机', '欢喜', '欣慰', '满意', '跳跃', '诚心', '称心', '如意', '怡然', '娇气', '无奈', '无语', '激动', '愤怒', '美好', '感动', '激情', '激昂', '震动', '虚拟', '超级', '寒冷', '精明', '明理', '犹豫', '忧郁', '寂寞', '奋斗', '勤奋', '现代', '过时', '稳重', '热情', '含蓄', '开放', '无辜', '多情', '纯真', '拉长', '热心', '从容', '体贴', '风中', '曾经', '追寻', '儒雅', '优雅', '开朗', '外向', '内向', '清爽', '文艺', '长情', '平常', '单身', '伶俐', '高大', '懦弱', '柔弱', '爱笑', '乐观', '耍酷', '酷炫', '神勇', '年轻', '唠叨', '瘦瘦', '无情', '包容', '顺心', '畅快', '舒适', '靓丽', '负责', '背后', '简单', '谦让', '彩色', '缥缈', '欢呼', '生动', '复杂', '慈祥', '仁爱', '魔幻', '虚幻', '淡然', '受伤', '雪白', '高高', '糟糕', '顺利', '闪闪', '羞涩', '缓慢', '迅速', '优秀', '聪明', '含糊', '俏皮', '淡淡', '坚强', '平淡', '欣喜', '能干', '灵巧', '友好', '机智', '机灵', '正直', '谨慎', '俭朴', '殷勤', '虚心', '辛勤', '自觉', '无私', '无限', '踏实', '老实', '现实', '可靠', '务实', '拼搏', '个性', '粗犷', '活力', '成就', '勤劳', '单纯', '落寞', '朴素', '悲凉', '忧心', '洁净', '清秀', '自由', '小巧', '单薄', '贪玩', '刻苦', '干净', '壮观', '和谐', '文静', '调皮', '害羞', '安详', '自信', '端庄', '坚定', '美满', '舒心', '温暖', '专注', '勤恳', '美丽', '腼腆', '优美', '甜美', '甜蜜', '整齐', '动人', '典雅', '尊敬', '舒服', '妩媚', '秀丽', '喜悦', '甜美', '彪壮', '强健', '大方', '俊秀', '聪慧', '迷人', '陶醉', '悦耳', '动听', '明亮', '结实', '魁梧', '标致', '清脆', '敏感', '光亮', '大气', '老迟到', '知性', '冷傲', '呆萌', '野性', '隐形', '笑点低', '微笑', '笨笨', '难过', '沉静', '火星上', '失眠', '安静', '纯情', '要减肥', '迷路', '烂漫', '哭泣', '贤惠', '苗条', '温婉', '发嗲', '会撒娇', '贪玩', '执着', '眯眯眼', '花痴', '想人陪', '眼睛大', '高贵', '傲娇', '心灵美', '爱撒娇', '细腻', '天真', '怕黑', '感性', '飘逸', '怕孤独', '忐忑', '高挑', '傻傻', '冷艳', '爱听歌', '还单身', '怕孤单', '懵懂'];
    $do = ["的", "爱", "", "与", "给", "扯", "和", "用", "方", "打", "就", "迎", "向", "踢", "笑", "闻", "有", "等于", "保卫", "演变"];
    $wei = ['嚓茶', '凉面', '便当', '毛豆', '花生', '可乐', '灯泡', '哈密瓜', '野狼', '背包', '眼神', '缘分', '雪碧', '人生', '牛排', '蚂蚁', '飞鸟', '灰狼', '斑马', '汉堡', '悟空', '巨人', '绿茶', '自行车', '保温杯', '大碗', '墨镜', '魔镜', '煎饼', '月饼', '月亮', '星星', '芝麻', '啤酒', '玫瑰', '大叔', '小伙', '哈密瓜，数据线', '太阳', '树叶', '芹菜', '黄蜂', '蜜粉', '蜜蜂', '信封', '西装', '外套', '裙子', '大象', '猫咪', '母鸡', '路灯', '蓝天', '白云', '星月', '彩虹', '微笑', '摩托', '板栗', '高山', '大地', '大树', '电灯胆', '砖头', '楼房', '水池', '鸡翅', '蜻蜓', '红牛', '咖啡', '机器猫', '枕头', '大船', '诺言', '钢笔', '刺猬', '天空', '飞机', '大炮', '冬天', '洋葱', '春天', '夏天', '秋天', '冬日', '航空', '毛衣', '豌豆', '黑米', '玉米', '眼睛', '老鼠', '白羊', '帅哥', '美女', '季节', '鲜花', '服饰', '裙子', '白开水', '秀发', '大山', '火车', '汽车', '歌曲', '舞蹈', '老师', '导师', '方盒', '大米', '麦片', '水杯', '水壶', '手套', '鞋子', '自行车', '鼠标', '手机', '电脑', '书本', '奇迹', '身影', '香烟', '夕阳', '台灯', '宝贝', '未来', '皮带', '钥匙', '心锁', '故事', '花瓣', '滑板', '画笔', '画板', '学姐', '店员', '电源', '饼干', '宝马', '过客', '大白', '时光', '石头', '钻石', '河马', '犀牛', '西牛', '绿草', '抽屉', '柜子', '往事', '寒风', '路人', '橘子', '耳机', '鸵鸟', '朋友', '苗条', '铅笔', '钢笔', '硬币', '热狗', '大侠', '御姐', '萝莉', '毛巾', '期待', '盼望', '白昼', '黑夜', '大门', '黑裤', '钢铁侠', '哑铃', '板凳', '枫叶', '荷花', '乌龟', '仙人掌', '衬衫', '大神', '草丛', '早晨', '心情', '茉莉', '流沙', '蜗牛', '战斗机', '冥王星', '猎豹', '棒球', '篮球', '乐曲', '电话', '网络', '世界', '中心', '鱼', '鸡', '狗', '老虎', '鸭子', '雨', '羽毛', '翅膀', '外套', '火', '丝袜', '书包', '钢笔', '冷风', '八宝粥', '烤鸡', '大雁', '音响', '招牌', '胡萝卜', '冰棍', '帽子', '菠萝', '蛋挞', '香水', '泥猴桃', '吐司', '溪流', '黄豆', '樱桃', '小鸽子', '小蝴蝶', '爆米花', '花卷', '小鸭子', '小海豚', '日记本', '小熊猫', '小懒猪', '小懒虫', '荔枝', '镜子', '曲奇', '金针菇', '小松鼠', '小虾米', '酒窝', '紫菜', '金鱼', '柚子', '果汁', '百褶裙', '项链', '帆布鞋', '火龙果', '奇异果', '煎蛋', '唇彩', '小土豆', '高跟鞋', '戒指', '雪糕', '睫毛', '铃铛', '手链', '香氛', '红酒', '月光', '酸奶', '银耳汤', '咖啡豆', '小蜜蜂', '小蚂蚁', '蜡烛', '棉花糖', '向日葵', '水蜜桃', '小蝴蝶', '小刺猬', '小丸子', '指甲油', '康乃馨', '糖豆', '薯片', '口红', '超短裙', '乌冬面', '冰淇淋', '棒棒糖', '长颈鹿', '豆芽', '发箍', '发卡', '发夹', '发带', '铃铛', '小馒头', '小笼包', '小甜瓜', '冬瓜', '香菇', '小兔子', '含羞草', '短靴', '睫毛膏', '小蘑菇', '跳跳糖', '小白菜', '草莓', '柠檬', '月饼', '百合', '纸鹤', '小天鹅', '云朵', '芒果', '面包', '海燕', '小猫咪', '龙猫', '唇膏', '鞋垫', '羊', '黑猫', '白猫', '万宝路', '金毛', '山水', '音响', '尊云', '西安'];
    $tou_num = rand(0, 331);
    $do_num = rand(0, 19);
    $wei_num = rand(0, 327);
    $type = rand(0, 1);
    if ($type == 0) {
        $username = $tou[$tou_num] . $do[$do_num] . $wei[$wei_num];
    } else {
        $username = $wei[$wei_num] . $tou[$tou_num];
    }
    return $username; //输出生成昵称
}

/**
 * t函数用于过滤标签，输出没有html的干净的文本.
 * @param string text 文本内容
 * @return string 处理后内容
 */
function op_t($text)
{
    $text = nl2br($text);
    $text = real_strip_tags($text);
    $text = addslashes($text);
    $text = trim($text);
    return $text;
}

/**
 * 返回周几
 * @param $datetime
 * @return string
 */
function get_chinese_weekday($datetime): string
{
    try {
        if (is_numeric($datetime)) {
            $obj = new DateTime();
            $obj->setTimestamp($datetime);
        } else {
            $obj = new \DateTime($datetime);
        }
    } catch (Exception $e) {
        return '--';
    }
    $weeks = ['日', '一', '二', '三', '四', '五', '六'];
    return '星期' . $weeks[$obj->format('w')];

}

/**
 * 友好显示时间
 * @param      $the_time
 * @param null $now_time
 * @return false|string
 * @author  : 微尘 <yicmf@qq.com>
 * @datetime: 2019/3/7 9:18
 */
function time_friend($the_time, $now_time = null)
{
    if (is_null($now_time)) {
        $now_time = $_SERVER['REQUEST_TIME'];
    }
    $the_time = is_numeric($the_time) ? $the_time : strtotime($the_time);
    $dur = $now_time - $the_time;
    if ($dur < 0) {
        return date('Y-m-d', $the_time);
    } else {
        if ($dur < (60 * 15)) {
            return '刚刚';
        } else {
            if ($dur < 3600) {
                return floor($dur / 60) . '分钟前';
            } else {
                if ($dur < 86400) {
                    return floor($dur / 3600) . '小时前';
                } else {
                    if ($dur <= 86400 * 7) {//一周
                        return floor($dur / 86400) . '天前';
                    } else {
                        if ($dur <= 86400 * 30) {//一个月
                            return floor($dur / (86400 * 7)) . '周前';
                        } else {
                            if ($dur <= 86400 * 365) {
                                return floor($dur / (86400 * 30)) . '月前';
                            } else {
                                return floor($dur / (86400 * 365)) . '年前';
                            }
                        }
                    }
                }
            }
        }
    }
}


/**
 * 时间根据指定格式格式化.
 * @param string $time 时间
 * @param string $format 格式类型、默认是Config::get('database.datetime_format')
 * @return string
 * @author  : 微尘 <yicmf@qq.com>
 * @datetime: 2019/2/22 11:24
 */
function time_format($time = '', $format = '')
{
    try {
        $format = $format ?: Config::get('database.datetime_format');
        if (is_numeric($time)) {
            $obj = new DateTime();
            $obj->setTimestamp($time);
        } else {
            $obj = new \DateTime($time);
        }
    } catch (Exception $e) {
        return '--';
    }
    return $obj->format($format);
}

/**
 * 格式化字节大小.
 * @param number $size 字节数
 * @param string $delimiter 数字和单位分隔符
 * @return string 格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 函数用于过滤不安全的html标签，输出安全的html.
 * @param string $text 待过滤的字符串
 * @param string $type 保留的标签格式
 * @return string 处理后内容
 */
function op_h($text, $type = 'html')
{
    // 无标签格式
    $text_tags = '';
    //只保留链接
    $link_tags = '<a>';
    //只保留图片
    $image_tags = '<img>';
    //只存在字体样式
    $font_tags = '<i><b><u><s><em><strong><font><big><small><sup><sub><bdo><h1><h2><h3><h4><h5><h6>';
    //标题摘要基本格式
    $base_tags = $font_tags . '<p><br><hr><a><img><map><area><pre><code><q><blockquote><acronym><cite><ins><del><center><strike>';
    //兼容Form格式
    $form_tags = $base_tags . '<form><input><textarea><button><select><optgroup><option><label><fieldset><legend>';
    //内容等允许HTML的格式
    $html_tags = $base_tags . '<ul><ol><li><dl><dd><dt><table><caption><td><th><tr><thead><tbody><tfoot><col><colgroup><div><span><object><embed><param>';
    //专题等全HTML格式
    $all_tags = $form_tags . $html_tags . '<!DOCTYPE><meta><html><head><title><body><base><basefont><script><noscript><applet><object><param><style><frame><frameset><noframes><iframe>';
    //过滤标签
    $text = real_strip_tags($text, ${$type . '_tags'});
    // 过滤攻击代码
    if ($type != 'all') {
        // 过滤危险的属性，如：过滤on事件lang js
        while (preg_match('/(<[^><]+)(ondblclick|onclick|onload|onerror|unload|onmouseover|onmouseup|onmouseout|onmousedown|onkeydown|onkeypress|onkeyup|onblur|onchange|onfocus|action|background|codebase|dynsrc|lowsrc)([^><]*)/i', $text, $mat)) {
            $text = str_ireplace($mat[0], $mat[1] . $mat[3], $text);
        }
        while (preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat)) {
            $text = str_ireplace($mat[0], $mat[1] . $mat[3], $text);
        }
    }
    return $text;
}

/**
 * 过滤函数，别名函数，op_t的别名
 */
function text($text)
{
    return op_t($text);
}

/**
 * 过滤函数，别名函数，op_h的别名
 */
function html($text)
{
    return op_h($text);
}

function real_strip_tags($str, $allowable_tags = '')
{
    $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
    return strip_tags($str, $allowable_tags);
}

/**
 * 加密数字
 * @param $user_id
 * @return string
 * @author  : 微尘 <yicmf@qq.com>
 * @datetime: 2019/4/24 17:42
 */
function code_encode($user_id)
{
    static $source_string = 'E5FCG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    $num = $user_id;
    $code = '';
    while ($num > 0) {
        $mod = $num % 34;
        $num = ($num - $mod) / 34;
        $code = $source_string[$mod] . $code;
    }
    if (empty($code[3]))
        $code = str_pad($code, 5, 'D', STR_PAD_LEFT);
    return strtolower($code);
}

/**
 * 解密数字
 * @param $code
 * @return float|int
 * @author  : 微尘 <yicmf@qq.com>
 * @datetime: 2019/4/24 17:42
 */
function code_decode($code)
{
    $code = strtoupper($code);
    static $source_string = 'E5FCG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    if (strrpos($code, 'D') !== false)
        $code = substr($code, strrpos($code, 'D') + 1);
    $len = strlen($code);
    $code = strrev($code);
    $num = 0;
    for ($i = 0; $i < $len; $i++) {
        $num += strpos($source_string, $code[$i]) * pow(34, $i);
    }
    return $num;
}

/**
 * 内容转换函数
 * @param string $message 内容模板
 * @param array $param 内容参数数组
 * @return string 通知内容
 */
function string_replace($content, $param)
{
    if (!is_array($param))
        return false;
    foreach ($param as $k => $v) {
        $content = str_replace('{$' . $k . '}', $v, $content);
    }
    return $content;
}

/**
 * 获取图片信息
 * @param number $id 图片的id
 * @param string $field 要获取的字段，默认为url
 * @return string
 * @author 微尘 <yicmf@qq.com>
 */
function get_image($id = 0, $field = 'url')
{
    $info = \app\model\file\Image::where('id', $id)->find();
    return empty($info[$field]) ? '' : $info[$field];
}

/**
 * 生成加密密钥.
 */
function build_encrypt_key($long = 32)
{
    $chars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $chars .= '`~!@#$%^&*()_+-=[]{};:"|,.<>/?';
    $chars = str_shuffle($chars);
    return substr($chars, 0, $long);
}

/**
 * 获取类中非继承方法和重写方法
 * 只获取在本类中声明的方法，包含重写的父类方法，其他继承自父类但未重写的，不获取
 * 例
 * class A{
 *        public function a1(){}
 *        public function a2(){}
 * }
 * class B extends A{
 *        public function b1(){}
 *        public function a1(){}
 * }
 * get_current_class_methods('B')返回方法名b1和a1，a2虽然被B继承了，但未重写，故不返回
 * get_current_class_methods(__CLASS__).
 * @param string $classname 类名
 * @param string $access public or protected  or private or final 方法的访问权限
 * @return array(methodname=>access) or array(methodname) 返回数组，如果第二个参数有效，
 *                                   则返回以方法名为key，访问权限为value的数组
 * @see  使用了命名空间，故在new 时类前加反斜线；如果此此函数不是作为类中方法使用，可能由于权限问题，
 *                                   只能获得public方法
 */
function get_current_class_methods($classname, $access = null)
{
    $class = new \ReflectionClass($classname);
    $methods = $class->getMethods();
    $returnArr = [];
    foreach ($methods as $value) {
        if ($value->class == $classname) {
            if ($access != null) {
                $methodAccess = new \ReflectionMethod($classname, $value->name);
                switch ($access) {
                    case 'public':
                        if ($methodAccess->isPublic()) {
                            $returnArr[$value->name] = 'public';
                        }
                        break;
                    case 'protected':
                        if ($methodAccess->isProtected()) {
                            $returnArr[$value->name] = 'protected';
                        }
                        break;
                    case 'private':
                        if ($methodAccess->isPrivate()) {
                            $returnArr[$value->name] = 'private';
                        }
                        break;
                    case 'final':
                        if ($methodAccess->isFinal()) {
                            $returnArr[$value->name] = 'final';
                        }
                        break;
                }
            } else {
                array_push($returnArr, $value->name);
            }
        }
    }
    return $returnArr;
}

/**
 * 根据用户ID获取用户信息.
 * @param int $user 用户ID
 * @param string $field 获取用户的字段，默认是nickname
 * @return mixed
 */
function get_user_info($user_id, $field = 'nickname')
{
    static $list;
    /* 获取缓存数据 */
    if (empty($list)) {
        $list = Cache::get('sys_user_info_list');
    }
    /* 查找用户信息 */
    $key = "u{$user_id}";
    if (isset($list[$key])) { //已缓存，直接使用
        $name = $list[$key][$field];
    } else { //调用接口获取用户信息
        $user = User::find($user_id);
        if ($user) {
            $list[$key] = $user->toArray();
            $name = $user[$field];
            /* 缓存用户 */
            $count = count($list);
            $max = Config::get('ucenter.user_max_cache');
            while ($count-- > $max) {
                array_shift($list);
            }
            Cache::set('sys_user_info_list', $list);
        } else {
            $name = '';
        }
    }
    return $name;
}

/**
 * 获取导航URL.
 * @param string $url 导航URL
 * @return string 解析或的url
 */
function get_nav_url($url, $module = 'Home')
{
    switch ($url) {
        case strpos($url, 'http'):
        case '#' === substr($url, 0, 1):
            break;
        //         case '/' === substr($url, 0, 1):
        //             break;
        default:
            $url = url($url);
            break;
    }
    return $url;
}

function to_cny($jp)
{
    return ceil($jp * config('store.yen_to_cny') * 100) / 100;
}

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start, $length, $charset = 'utf-8', $suffix = false)
{
    if (function_exists('mb_substr')) {
        $slice = mb_substr($str, $start, $length, $charset);
    } elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
        if (false === $slice) {
            $slice = '';
        }
    } else {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = implode('', array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice . '...' : $slice;
}

/**
 * 系统加密方法.
 * @param string $data 要加密的字符串
 * @param string $key 加密密钥
 * @param int $expire 过期时间 单位 秒
 * @return string
 */
function think_encrypt($data, $key = '', $expire = 0)
{
    $key = md5(empty($key) ? Config::get('ucenter.data_auth_key') : $key);
    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }
    return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($str));
}

/**
 * 系统解密方法.
 * @param string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param string $key 加密密钥
 * @return string
 */
function think_decrypt($data, $key = '')
{
    $key = md5(empty($key) ? Config::get('ucenter.data_auth_key') : $key);
    $data = str_replace(['-', '_'], ['+', '/'], $data);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);
    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}


/**
 * 对查询结果集进行排序.
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 *                       asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
    if (is_array($list)) {
        $refer = $resultSet = [];
        foreach ($list as $i => $data) {
            $refer[$i] = &$data[$field];
        }
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val) {
            $resultSet[] = &$list[$key];
        }
        return $resultSet;
    }
    return false;
}

/**
 * 把返回的数据集转换成Tree.
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = [];
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                //XXX:已经修复需要确认http://stackoverflow.com/posts/20053269/indirect-modification-of-overloaded-element-of-splfixedarray-has-no-effect
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    //                     $temp=& $list[$key];
                    //                     $temp[]=$temp;
                    //                     $parent[$child]=$temp;
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表.
 * @param array $tree 原来的树
 * @param string $child 孩子节点的键
 * @param string $order 排序显示的键，一般是主键 升序排列
 * @param array $list 过渡用的中间数组，
 * @return array 返回排过序的列表数组
 */
function tree_to_list($tree, $child = '_child', $order = 'id', &$list = [])
{
    if (is_array($tree)) {
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if (isset($reffer[$child])) {
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby = 'asc');
    }
    return $list;
}


/**
 * 将字符保密、隐藏输出，默认隐藏中间1/3
 * @param string $str
 * @param int $start 从第几个位置开始隐藏，默认1/3处
 * @param int $length 连续隐藏多少位，默认1/3
 * @return string
 * @author  : 微尘 <yicmf@qq.com>
 * @datetime: 2019/3/4 11:33
 */
function secrecy_show($str, $start = 2, $length = 5, $replacement = '*')
{
    $len = mb_strlen($str, 'utf-8');
    if ($len > intval($start + $length)) {
        $str1 = mb_substr($str, 0, $start, 'utf-8');
        $str2 = mb_substr($str, intval($start + $length), NULL, 'utf-8');
    } else {
        $str1 = mb_substr($str, 0, 1, 'utf-8');
        $str2 = mb_substr($str, $len - 1, 1, 'utf-8');
        $length = $len - 2;
    }
    $new_str = $str1;
    for ($i = 0; $i < $length; $i++) {
        $new_str .= $replacement;
    }
    $new_str .= $str2;
    return $new_str;
}

if (!function_exists('getallheaders')) {
    function getallheaders()
    {
        $headers = array();
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-',
                    ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}
/**
 * ajax数据加密
 * @param array $data
 * @return Response
 */
function response_ajax($data, $code = 200, $header = [], $options = [])
{
    $header['timestamp'] = time();
    $header['route'] = request()->controller() . '.' . request()->action();
//    $header['version'] = '1.0';
//    $header['sign_type'] = 'md5';
    // 临时加密方式
//    $header['sign'] = md5(md5(json_encode($data)) . 'key');
    if (!empty($data['message'])) {
        $data['message'] = lang($data['message']);
    } else {
        $data['message'] = lang('success');
    }
    return Response::create($data, 'json', $code)->header($header)->options($options);
}
